Add-Type -AssemblyName System.Net

$listener = New-Object System.Net.HttpListener
$prefix = "http://localhost:8000/"
$listener.Prefixes.Add($prefix)
$listener.Start()
Write-Host "本地服务器已启动: $prefix"

$root = (Get-Location).Path

function Get-ContentType($path) {
  switch ([System.IO.Path]::GetExtension($path).ToLower()) {
    '.html' { 'text/html' }
    '.js'   { 'text/javascript' }
    '.css'  { 'text/css' }
    '.json' { 'application/json' }
    '.png'  { 'image/png' }
    '.jpg'  { 'image/jpeg' }
    '.jpeg' { 'image/jpeg' }
    '.gif'  { 'image/gif' }
    default { 'application/octet-stream' }
  }
}

while ($true) {
  try {
    $context = $listener.GetContext()
    $request = $context.Request
    $response = $context.Response

    $path = $request.Url.AbsolutePath.TrimStart('/')
    if ([string]::IsNullOrEmpty($path)) { $path = 'index.html' }

    $filePath = Join-Path $root $path

    if (Test-Path $filePath) {
      $bytes = [System.IO.File]::ReadAllBytes($filePath)
      $response.ContentType = Get-ContentType -path $filePath
      $response.ContentLength64 = $bytes.Length
      $response.OutputStream.Write($bytes, 0, $bytes.Length)
    } else {
      $response.StatusCode = 404
      $msg = [System.Text.Encoding]::UTF8.GetBytes("Not Found")
      $response.OutputStream.Write($msg, 0, $msg.Length)
    }
    $response.OutputStream.Close()
  } catch {
    Write-Host "服务器错误: $_"
  }
}